using System;
using System.Collections.Generic;
using System.Text;

using System.Threading;

namespace JoyStickController
{
    public delegate void JoystickStateDelegate(JoyState state);

    public class JoystickController
    {
//        private CaterpillarController caterpillarController;
        
        public event JoystickStateDelegate NewJoystickState;

        private int delayInMilliSecs;
        private Joystick joystick;
        private volatile bool started;

        public int DelayInMilliSecs
        {
            get { return delayInMilliSecs; }
            set { delayInMilliSecs = value; }
        }

        public JoystickController(int delayInMilliSecs)
        {
            this.delayInMilliSecs = delayInMilliSecs;
            this.joystick = new Joystick();
        }

        public void Start()
        {
            if (!started)
            {
                started = true;
                Thread thread = new Thread(new ThreadStart(BackgroundThread));
                thread.IsBackground = true;
                thread.Start();
            }
        }

        private void BackgroundThread()
        {
            while (started)
            {
                if (NewJoystickState != null)
                    NewJoystickState(this.joystick.State);
                //JoyState joyState = this.joystick.State;
                //double left = (double)joyState.Y / 2.0 - (double)joyState.X / 2.0;
                //double right = (double)joyState.Y / 2.0 + (double)joyState.X / 2.0;
                //caterpillarController.Move(left, right, delayInMilliSecs);
                Thread.Sleep(delayInMilliSecs);
            }

        }
        public void Stop()
        {
            started = false;
        }
    }
}
